package org.jeecg.modules.xxgx.common.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

/**
 * 支持对本地及远程共享文件进行读写操作
 * @author Jensen
 *
 */
public class FileHelper {
	private static final String FILENOTFOUND = "未能找到文件:";
	private static final String READFILEERROR = "读取文件出现错误";
	private FileHelper(){}

	private static Logger logger = LoggerFactory.getLogger(FileHelper.class);
	/**
	 * 读取文件
	 * @param filePath
	 * @return
	 */
	public static byte[] read(String filePath)  
    {  
    	BufferedInputStream in=null;
    	FileInputStream fIn = null;
        try
        {  
        	String fileFullPath = ensurePath(filePath);
        	int fileLength = 0;
        		File fileOriginal = new File(fileFullPath);
        		if(!fileOriginal.exists())
        		{
					logger.error("文件读取错误", FILENOTFOUND+fileFullPath);
                     return new byte[0];  
        		}
        		fileLength = (int)fileOriginal.length();
        		fIn = new FileInputStream(fileOriginal);
        		in = new BufferedInputStream(fIn);

        	byte []ret = new byte[fileLength];
            int offset = 0; 
            int numRead = 0; 
            while(offset<ret.length&&(numRead=in.read(ret,offset,ret.length-offset))>=0) 
            { 
                offset+=numRead; 
            }

            in.close();
            fIn.close();
            return ret;
            
        }

        catch (Exception e)  
        {
			logger.error("文件读取错误", READFILEERROR+e.getMessage());
            return new byte[0];
        }
        finally {
        	try{
        		if(fIn!=null){
        			fIn.close();
        		}
        		if(in!=null){
        			in.close();
        		}
        	}catch(IOException ee){
				logger.error("文件读取错误", READFILEERROR+ee.getMessage());
        	}
        }
    }  
	/**
	 * 获取读文件对象
	 * @param filePath
	 * @return
	 */
	public static BufferedInputStream getBufferedReader(String filePath)  
    {  
		BufferedInputStream in=null;
    	FileInputStream fIn = null;
    	
        try  
        {  
        	String fileFullPath = ensurePath(filePath);
        		File fileOriginal = new File(fileFullPath);
        		if(!fileOriginal.exists())
        		{
					logger.error("文件读取错误", FILENOTFOUND+fileFullPath);
                     return null;  
        		}
        		fIn = new FileInputStream(fileOriginal);
        		in = new BufferedInputStream(fIn);

        	return in;
            
        }  
        catch (Exception e)  
        {
			logger.error("文件读取错误", READFILEERROR+e.getMessage());
            return null;
        }  
    }
  
	/**
	 * 存储文件
	 * @param filePath
	 * @return
	 */  
    public static Boolean save(String filePath, byte []data)  
    {  
        BufferedOutputStream out = null;  
        FileOutputStream fOut = null;
        try  
        {  
        	String fileFullPath = ensurePath(filePath);
        		File file = new File(fileFullPath);
        		if(!file.getParentFile().exists()){
        		    file.getParentFile().mkdirs();
        		}
				if(!file.exists()&&!file.createNewFile())
				{
					logger.error("文件错误", "创建文件失败!");
				}
				fOut = new FileOutputStream(file);
				out=new BufferedOutputStream(fOut);

			out.write(data);
			out.flush();
			out.close();;
			fOut.close();
			return true;
        }  
        catch (Exception e)  
        {
			logger.error("文件错误", "存储文件发生错误："+e.getMessage());
            return false;
        } 
        finally{
        	try{
        		if(fOut!=null){
        			fOut.close();
        		}
        		if(out!=null){
        			out.close();
        		}
        	}catch(IOException ee){
				logger.error("文件错误", READFILEERROR+ee.getMessage());
        	}
        }
    }  
    /**
     * 删除文件
     * @param filePath
     * @return
     */
    public static Boolean delete(String filePath)
    {
    	try{
    		String fileFullPath = ensurePath(filePath);
    		Boolean result = true;
    			File fileOriginal = new File(fileFullPath);
    			if(fileOriginal.exists())
    			{
    				result = fileOriginal.delete();
    			}
    		return result;
    	}catch(Exception e)
    	{
			logger.error("删除文件错误", e.getMessage());
    		return false;
    	}
    }
    /**
     * 获取文件大小
     * @param filePath
     * @return
     */
    public static Long getFileSize(String filePath)
    {
    	try{
    		String fileFullPath = ensurePath(filePath);
    		Long result = 0L;
    			File fileOriginal = new File(fileFullPath);
    			if(fileOriginal.exists())
    			{
    				result = fileOriginal.length();
    			}
    		return result;
    	}catch(Exception e)
    	{
			logger.error("获取文件错误", e.getMessage());
    		return 0L;
    	}
    }
    /**
     * 获取文件最后修改时间
     * @param filePath
     * @return
     */
    public static Date getLastModified(String filePath)
    {
    	try{
    		String fileFullPath = ensurePath(filePath);
    		Date result = new Date();
    			File fileOriginal = new File(fileFullPath);
    			if(fileOriginal.exists())
    			{
    				result = new Date(fileOriginal.lastModified());
    			}
    		return result;
    	}catch(Exception e)
    	{
			logger.error("获取文件最后修改时间", e.getMessage());
    		return new Date();
    	}
    }
    /**
     * 判断路径是否为远程文件
     * @param fileFullPath
     * @return
     */
    private static Boolean isRemote(String fileFullPath)
    {
    	return fileFullPath.toLowerCase().startsWith("smb:")?true:false;
    }
    /**
     * 确保路径与当前操作系统匹配
     * @param path
     * @return
     */
    private static String ensurePath(String path)
	{
		String ret;
		if(isLinux()||path.toLowerCase().startsWith("smb:"))
		{
			ret = path.replace("\\", "/");
		}
		else
		{
			ret = path.replace("/", "\\");
		}
		return ret;
	}
	/**
	 * 判断当前操作系统类型
	 * @return
	 */
	public static Boolean isLinux()
	{
		String osName = System.getProperty("os.name");
		return "win".startsWith(osName.toLowerCase())?false:true;
	}

	/**
	 * MultipartFile to File
	 * @param file
	 * @throws Exception
	 */
	public static File MutlFileToFile(MultipartFile file) throws Exception {
		File toFile = null;
		if(file.equals("")||file.getSize()<=0){
			file = null;
		}else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		return toFile;
	}

    public static File MutlFileToFile(MultipartFile file,String destFileName) throws Exception {
        File fileObj=new File(destFileName);
        file.transferTo(fileObj);
        return  fileObj;
    }

	public static String getUploadTempPath(String dirName)  {
	    try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) path = new File("");
            System.out.println("path:" + path.getAbsolutePath());

            String sPath = "static/tmp/";
            if (StringUtils.isNotEmpty(dirName)) {
                sPath = sPath + dirName + "/";
            }
            //如果上传目录为/static/images/upload/，则可以如下获取：
            File upload = new File(path.getAbsolutePath(), sPath);
            if (!upload.exists()) upload.mkdirs();
            return upload.getAbsolutePath();
        }catch (Exception ex){
	        ex.getStackTrace();
	        return "";
        }
    }
	public static void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
